<template>
  <div class="charts" v-if="dataArray.length>0">
    <LineChart v-for="(item, idx) in dataArray" :data="item" :id="setChartId(idx)" :ifPredict="ifPredict" :mode="actuallyMode" :key="idx">
    </LineChart>
  </div>
  <div class="info" v-if="dataArray.length==0">暂无该时段的数据</div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { computed, inject, onMounted, reactive, ref, watch } from 'vue';
import { reqMonitorData } from '@/api/monitor'
import LineChart from './LineChart/index.vue'
import { getDaysDifference } from '@/constant/date'
import useOperationStore from '../../store/operation';

// 切换业务的数据对接处理
let operationStore=useOperationStore()
let operationId = ref(operationStore.data.length>0?operationStore.data[operationStore.index].id:'')
operationStore.$subscribe(async(mutation, state)=>{
  operationId.value=operationStore.data[operationStore.index].id
  await initData()
})
// 是否预测数据
let ifPredict = ref(false);
// 数据模式
let mode = ref('day')
// 存储折线图表数据
let dataArray = reactive([])
// 动态模式
let actuallyMode = computed(() => {
    let diff=getDaysDifference(props.startTime,props.endTime)
    if (diff<=1){
      return "day"
    }
    else if(diff<=90){
      return "month"
    }
    else{
      return "year"
    }
})
// 组件参数
let props = defineProps({
  mode: {
    type: String,
    default: "day"
  },
  ifPredict: {
    type: Boolean,
    default: false
  },
  startTime: {
    type: String,
    default: null,
  },
  endTime: {
    type: String,
    default: null
  }
})

// 设置图标id
const setChartId = (idx) => {
  return `echarts${idx}`
}
// 加载数据
const initData = async () => {
  if (props.startTime == null || props.endTime == null) return
  // 数据请求
  // 将startTime和endTime处理成yyyy-MM-dd HH:mm:ss格式
  const startTime = props.startTime.replace('+', ' ')
  const endTime = props.endTime.replace('+', ' ')
  let res = await reqMonitorData(operationId.value, startTime, endTime, props.ifPredict)
  // code 0:成功引入，1：token过期，2：其它错误
  switch (res.code) {
    case 0:
      dataArray.splice(0, dataArray.length)
      dataArray.push(...res.data)
      break;
    case 1:
      setTimeout(() => { $router.push('/login') }, 1000)
      break;
  }
}
// 更新组件参数
watch(props, async (newVal, oldVal) => {
  ifPredict.value = newVal.ifPredict
  mode.value = newVal.mode
  if (operationId.value != null) {
    await initData()
  }
})
onMounted(async () => {
  ifPredict.value = props.ifPredict
  mode.value = props.mode
  if (operationId.value != null) {
    await initData()
  }
})
</script>

<style lang="scss" scoped>
.charts {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(3, 33%);
  grid-template-rows: repeat(3, 33%);
  gap: 10px;
}
.info{
  flex:1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40px;
  color: gray;
  font-weight: 700;
}
</style>